package zapx

import (
	"log"
	"os"
	"strings"
	"sync"

	"gitee.com/chewel/hermes/pkg/journal"
	"go.uber.org/zap"
)

const (
	EnvironmentDev  string = "dev"
	EnvironmentProd string = "prod"
)

var (
	once sync.Once
)

func InitLogger() journal.ILogger {
	if journal.L() != nil {
		return journal.L()
	}

	once.Do(func() {
		env := strings.ToLower(os.Getenv("GO_ENV"))
		if strings.TrimSpace(env) == "" {
			env = EnvironmentDev
		}

		cfg := zap.NewDevelopmentConfig()
		if env == EnvironmentProd {
			cfg = zap.NewProductionConfig()
		}

		logger, err := cfg.Build()
		if err != nil {
			log.Fatalf("创建日志组件出错: %v", err)
		}

		zap.ReplaceGlobals(logger)
		defaultLogger := NewLogger(logger)
		journal.ReplaceGlobals(defaultLogger)
	})
	return journal.L()
}
